const sendbtn = document.querySelector("#send");
const msg_log_box = document.querySelector(".msg-log-box");
const msg_input_box = document.querySelector(".msg-input-box");
const member_list = document.querySelector(".member-list");
const login_form = document.querySelector(".right");

function Message(name, html, pos) {
    var msg = document.createElement("div");
    msg.classList.add("msg");
    if (pos == false) {
        msg.classList.add("msg-self");
    }
    var msg_name = document.createElement("div");
    msg_name.classList.add("msg-name");
    msg_name.innerText = name;
    msg.appendChild(msg_name);
    var msg_bub = document.createElement("div");
    msg_bub.classList.add("msg-bub");
    msg_bub.innerHTML = html;
    msg.appendChild(msg_bub);
    this.html = msg;
    this.name = msg_name;
    this.bub = msg_bub;
}
var usename = "";
var socket = io();
document.querySelector("#loginbtn").addEventListener("click", function (e) {
    e.preventDefault();
    console.log(login_form.children["use"].value);
    if (
        login_form.children["use"].value != "" &&
        login_form.children["pwd"].value != ""
    ) {
        var ajax = new XMLHttpRequest();
        ajax.onreadystatechange = function () {
            if (
                ajax.readyState == 4 &&
                ajax.status == 200 &&
                ajax.responseText == "login succeed"
            ) {
                document.querySelector(".login").classList.add("hidden");
                document.querySelector(".chat-box").classList.remove("hidden");
                usename = login_form.children["use"].value;
                //发送昵称给后端
                socket.emit("join", usename);
            }
        };
        ajax.open("POST", "/login", true);
        ajax.setRequestHeader("Content-type", "application/json");
        ajax.send(
            JSON.stringify({
                use: login_form.children["use"].value,
                pwd: login_form.children["pwd"].value,
            })
        );
    }
});

//收到服务器发来的join事件时
socket.on("join", function (user) {
    var div = document.createElement("div");
    div.innerHTML = user + " 加入了群聊";
    member_list.appendChild(div);
});

socket.on("message", function (msg) {
    var pos = true;
    if (msg.sender == usename) {
        pos = false;
    }
    var newmsg = new Message(msg.sender, msg.content, pos);
    msg_log_box.appendChild(newmsg.html);
});

sendbtn.addEventListener("click", function () {
    if (msg_input_box.innerHTML != "") {
        socket.emit("message", {
            sender: usename,
            content: msg_input_box.innerHTML,
        }); //将消息发送给服务器
        msg_input_box.innerHTML = "";
    }
});
